<template>
  <div class="form-box-bg">
    <div class="form-box">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" status-icon>
        <h2 style="text-align: center; color: dodgerblue">注 册</h2>
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" :prefix-icon="User"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" show-password placeholder="请输入密码"
                    autocomplete="new-password" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item prop="confirm">
          <el-input v-model="form.confirm" show-password placeholder="请确认密码"
                    autocomplete="new-password" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"
                    :prefix-icon="Message"></el-input>
        </el-form-item>
        <el-form-item prop="emailCode">
          <div style="display: flex">
            <el-input style="flex: 1" placeholder="请输入邮箱验证码" v-model="form.emailCode" maxlength="6"></el-input>
            <el-button style="width: 100px;margin-left: 5px" type="danger" @click="sendEmailCode" :disabled="time > 0">
              点击发送<span
                v-if="time">({{ time }})</span></el-button>
          </div>
        </el-form-item>
        <el-form-item prop="name">
          <el-input v-model="form.name" placeholder="请输入昵称"
                    :prefix-icon="MagicStick"></el-input>
        </el-form-item>
        <div style="margin-bottom: 0.83em">
          <el-button style="width: 100%" type="primary" @click="register">注册</el-button>
        </div>
        <div style="text-align: right">
          <el-button type="primary" link @click="router.push('/login')">已有账号?请登录</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
// import { FormInstance, FormRules } from 'element-plus'
import {User, Lock, MagicStick, Message} from '@element-plus/icons-vue'
import router from "@/router";
import request from "@/utils/request";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user";

const ruleFormRef = ref()
const form = reactive({})
const store = useUserStore()
const time = ref(0)
const interval = ref(-1)

const confirmPassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请确认密码'))
  }
  if (form.password != value) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const reg = /^\w+((.\w+)|(-\w+))@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+).[A-Za-z0-9]+$/
const checkEmail = (rule, value, callback) => {
  if (!reg.test(value)) {
    return callback('邮箱不合法,请重新输入!');
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
  ],
  confirm: [
    {validator: confirmPassword, trigger: 'blur'},
  ],
  email: [
    {validator: checkEmail, trigger: 'blur'},
  ],
  emailCode: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
  ]
})

const sendEmailCode = () => {
  if (!reg.test(form.email)) {
    ElMessage.warning("请输入合法的邮箱");
    return;
  }
  //清空定时器
  if(interval.value>=0){
    clearInterval(interval.value)
  }
  //设置验证码点击定时器
  time.value = 10;
  interval.value = setInterval(() => {
    if (time.value > 0) {
      time.value--;
    }
  }, 1000)

  request.get("/emailregister", {
    params: {
      email: form.email,
      type: 'REGISTER',
    }
  }).then(res => {
    if (res.code === '200') {
      ElMessage.success('发送成功，有效期5分钟');
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const register = () => {
  ruleFormRef.value.validate(valid => {
    //当valid === true 时,就可以调用登录接口了
    if (valid) {
      request.post("/register", form).then(res => {
        console.log(res)
        if (res.code === '200') {
          const store = useUserStore()
          //前端批量存储用户数据，存储到缓存
          store.setUser(res.data)
          ElMessage.success('注册成功!');
          router.push('/')
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
  })
}
</script>

<style scoped>
.form-box {
  width: 400px;
  border-radius: 10px;
  margin: 0 auto;
  box-shadow: 0 0 5px -2px rgba(0, 0, 0, .5);
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 50px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

.form-box-bg {
  height: 100vh;
  overflow: hidden;
  position: relative;
  background-image: linear-gradient(to top, #a8edea 0%, #fed6e3 100%);
}
</style>